package top.infopub.mgr.bpa.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.bpa.BpaPublicProInfoDto;
import top.infopub.enums.bpa.BpaProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.mgr.bpa.dao.BpaWeekEffectDetailDao;
import top.infopub.mgr.bpa.dao.BpaWeekEffectPlanDao;
import top.infopub.mgr.bpa.domain.WeekEffectPlanDomain;
import top.infopub.mgr.bpa.dto.BpaWeekEffectPlanDto;
import top.infopub.mgr.bpa.jsonVo.BpaWeekEffectPlanJsonVo;
import top.infopub.mgr.bpa.service.BpaProcessManageService;
import top.infopub.mgr.bpa.service.BpaWeekEffectPlanService;
import top.infopub.mgr.bpa.vo.BpaWeekEffectDetail;
import top.infopub.mgr.bpa.vo.BpaWeekEffectPlan;
import top.infopub.mgr.bpa.vo.EffectPlanPublicVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.ProjectInfoService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.util.FileAttrUtils;
import top.infopub.mgr.util.ReflectBeanUtils;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by wurz on 2bpaWeekEffectPlanDao.21/6/2bpaWeekEffectPlanDao..
 */
@Service
public class BpaWeekEffectPlanServiceImpl implements BpaWeekEffectPlanService {
    @Resource
    private BpaWeekEffectPlanDao bpaWeekEffectPlanDao;
    @Resource
    private BpaWeekEffectDetailDao bpaWeekEffectDetailDao;
    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private OAFlowService oaFlowService;

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private BpaProcessManageService bpaProcessManageService;

    @Autowired
    private ProjectInfoService projectInfoService;

    @Override
    public int insert(BpaWeekEffectPlan bpaWeekEffectPlan) {
        return bpaWeekEffectPlanDao.insert(bpaWeekEffectPlan);
    }

    @Override
    public int deleteByPrimaryKey(String sguid) {
        return bpaWeekEffectPlanDao.deleteByPrimaryKey(sguid);
    }

    @Override
    public int delete(BpaWeekEffectPlan bpaWeekEffectPlan) {
        return bpaWeekEffectPlanDao.delete(bpaWeekEffectPlan);
    }

    @Override
    public int updateByPrimaryKey(BpaWeekEffectPlan bpaWeekEffectPlan) {
        return bpaWeekEffectPlanDao.updateByPrimaryKey(bpaWeekEffectPlan);
    }

    @Override
    public BpaWeekEffectPlan selectOne(String sguid) {
        return bpaWeekEffectPlanDao.selectOne(sguid);
    }

    @Override
    public Page<WeekEffectPlanDomain> selectList(Page<WeekEffectPlanDomain> page, EffectPlanPublicVo effectPlanPublicVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return bpaWeekEffectPlanDao.selectList(effectPlanPublicVo);
    }

    @Override
    public int selectCount(BpaWeekEffectPlan bpaWeekEffectPlan) {
        return bpaWeekEffectPlanDao.selectCount(bpaWeekEffectPlan);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RspVo edit(BpaWeekEffectPlanJsonVo jsonVo, Integer submitType, AuthorizationVO vo) {
        String id = jsonVo.getInfo().getId();
        BpaWeekEffectPlan weekEffePlan = new BpaWeekEffectPlan();
        if (StringUtils.isNotBlank(id)) {
            //校验数据是否存在
            BpaWeekEffectPlan tmpWep = this.selectOne(id);
            if (jsonVo == null) return RspVo.getFailureResponse(400, "周创效算数据不存在");
            //判断审批状态
            if (StringUtils.isNotBlank(tmpWep.getProcessStatus())
                    && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpWep.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpWep.getProcessStatus()))) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
            weekEffePlan = this.getUpdatePlanVo(jsonVo,vo);
            this.updateByPrimaryKey(weekEffePlan);
            weekEffePlan.setOaId(tmpWep.getOaId());
        } else {
            weekEffePlan = this.getInsertPlanVo(jsonVo,vo);
            bpaWeekEffectPlanDao.insert(weekEffePlan);
        }
        //更新详细列表
        List<BpaWeekEffectDetail> detailList = jsonVo.getWeekEffectDetails();
        bpaWeekEffectDetailDao.deleteByZdId(weekEffePlan.getId());
        if (detailList != null && detailList.size() > 0) {
            for (BpaWeekEffectDetail detail : detailList) {
                detail.setZdId(weekEffePlan.getId());
                bpaWeekEffectDetailDao.insert(detail);
            }
        }

        //更新附件表-MKT_PROJECT_ATTACHMENT--该处ID映射好
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(jsonVo.getFileAtt()!=null){
            String[] fileAtt = jsonVo.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = FileAttrUtils.createProjectFileAtta(weekEffePlan.getId(), file);
                attachmentList.add(attachment);
            }
        }
        //更新附件信息--根据不同类型的ProjectFileTypeEnum处理附件信息
        projectAttachmentDao.deleteByWhere(weekEffePlan.getId(), ProjectFileTypeEnum.FILE_TYPE158.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }
        if (submitType == 1) {
            //处理OA待办，主表里的OA_ID
            if (StringUtils.isNotBlank(weekEffePlan.getOaId())) {
                oaFlowService.finishOA(weekEffePlan.getOaId());
            }
            String detailJson = JSON.toJSONString(queryDetailById(weekEffePlan.getId()));
            //根据不同类型发起不同的流程，参考BpaProcessDetailTypeEnum
            bpaProcessManageService.sendProcess(BpaProcessDetailTypeEnum.PRO_NODE_TYPE34, detailJson, weekEffePlan.getId(), weekEffePlan.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }

    private BpaWeekEffectPlan getUpdatePlanVo(BpaWeekEffectPlanJsonVo jsonVo, AuthorizationVO auth){
        BpaWeekEffectPlanDto detailObject = jsonVo.getInfo();
        BpaWeekEffectPlan vo = ReflectBeanUtils.do2bo(detailObject,BpaWeekEffectPlan.class);
        vo.setUptBy(auth.getId());
        vo.setUptTime(new Date());
        return vo;
    }

    private BpaWeekEffectPlan getInsertPlanVo(BpaWeekEffectPlanJsonVo jsonVo,AuthorizationVO auth){
        BpaWeekEffectPlan temp = ReflectBeanUtils.do2bo(jsonVo.getInfo(), BpaWeekEffectPlan.class);
        Date date = new Date();
        temp.setAddBy(auth.getId());
        temp.setAddTime(date);
        temp.setUptTime(date);
        temp.setUptBy(auth.getId());
        temp.setCodes(IdFactory.getUUIDUpper());
        return temp;
    }

    @Override
    public BpaWeekEffectPlanJsonVo queryDetailById(String id) {
        BpaWeekEffectPlanJsonVo vo = new BpaWeekEffectPlanJsonVo();
        if (StringUtils.isNotBlank(id)) {
            BpaWeekEffectPlanDto dto = new BpaWeekEffectPlanDto();
            BpaWeekEffectPlan plan = bpaWeekEffectPlanDao.selectOne(id);
            BeanUtils.copyProperties(plan, dto);
            BpaPublicProInfoDto proInfo = projectInfoService.queryBpaProInfoByProCode(plan.getProCode());
            BeanUtils.copyProperties(proInfo, dto);
            vo.setInfo(dto);
            //基础信息--查询对应的，可以根据不同的类型查询，查询详情数据后把数据复制到Dto中
            //设置基础信息、详细列表、附件信息表
            BpaWeekEffectDetail param = new BpaWeekEffectDetail();
            param.setZdId(id);
            List<BpaWeekEffectDetail> details = bpaWeekEffectDetailDao.selectList(param);
            vo.setWeekEffectDetails(details);

            List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(id, ProjectFileTypeEnum.FILE_TYPE158.getCode(), null);
            vo.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
        } else {
            //查询项目列表
            vo.setProInfoList(setupProService.queryPublicProInfo());
        }
        return vo;
    }
}
